package com.qsmx.qingqiuticket.app.delegate.mem;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qsmx.core.delegates.AtmosDelegate;
import com.qsmx.core.net.HttpHelper;
import com.qsmx.core.net.callback.IError;
import com.qsmx.core.net.callback.IFailure;
import com.qsmx.core.net.callback.ISuccess;
import com.qsmx.core.util.CountDownTimerUtil;
import com.qsmx.core.util.StringUtil;
import com.qsmx.core.util.dialog.DialogUtil;
import com.qsmx.core.util.dimen.DimenUtil;
import com.qsmx.core.util.storage.AtmosPreference;
import com.qsmx.qingqiuticket.app.R;
import com.qsmx.qingqiuticket.app.databinding.DelegateMemTicketListBinding;
import com.qsmx.qingqiuticket.app.delegate.HomeDelegate;
import com.qsmx.qingqiuticket.app.delegate.adapter.MemPackageListAdapter;
import com.qsmx.qingqiuticket.app.entity.BaseEntity;
import com.qsmx.qingqiuticket.app.entity.MemPrintInfoEntity;
import com.qsmx.qingqiuticket.app.entity.MemTicketListEntity;
import com.qsmx.qingqiuticket.app.entity.PrintInfoEntity;
import com.qsmx.qingqiuticket.app.event.CheckTicketWaringEvent;
import com.qsmx.qingqiuticket.app.event.PrintFinishEvent;
import com.qsmx.qingqiuticket.app.fusion.FusionCode;
import com.qsmx.qingqiuticket.app.fusion.FusionData;
import com.qsmx.qingqiuticket.app.fusion.FusionPre;
import com.qsmx.qingqiuticket.app.net.HttpUrl;
import com.qsmx.qingqiuticket.app.util.CameraManager;
import com.qsmx.qingqiuticket.app.util.FileUtil;
import com.qsmx.qingqiuticket.app.util.LogUtils;
import com.qsmx.qingqiuticket.app.util.PrintUtil;
import com.qsmx.qingqiuticket.app.util.SaveHelper;
import com.qsmx.qingqiuticket.app.util.SoundPlayUtils;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class MemTicketListDelegate extends AtmosDelegate {

    private List<MemTicketListEntity.BodyBean.MachineTicketInfosBean> mPackageList;
    private List<MemPrintInfoEntity.BodyBean> mPrintData;
    private int mAllPrintTicketNum;
    private CountDownTimerUtil timer;
    private CountDownTimerUtil finishTimer;

    private DelegateMemTicketListBinding mBinding;
    private MemPackageListAdapter memPackageListAdapter;
    private MemPackageListAdapter cantMemPackageListAdapter;
    /**
     * 打印中弹窗
     */
    private Dialog mPrintTicketDialog;
    private AppCompatTextView tvTicketOutNum;
    private AppCompatTextView tvPrintGetTicket;
    private AppCompatTextView tvPrintFinishTime;
    private AppCompatTextView tvPrintStatus;
    private AppCompatTextView tvBackNow;
    private AppCompatTextView tvPrintErrorInfo;
    private AppCompatTextView tvRetry;

    @Override
    public Object setLayout() {
        return R.layout.delegate_mem_ticket_list;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mBinding = DelegateMemTicketListBinding.bind(rootView);

        mBinding.rlvSessionTicketList.setLayoutManager(new LinearLayoutManager(getContext()));
        memPackageListAdapter = new MemPackageListAdapter(getContext());
        mBinding.rlvSessionTicketList.setAdapter(memPackageListAdapter);

        mBinding.rlvCantSessionTicketList.setLayoutManager(new LinearLayoutManager(getContext()));
        cantMemPackageListAdapter = new MemPackageListAdapter(getContext());
        mBinding.rlvCantSessionTicketList.setAdapter(cantMemPackageListAdapter);

        if (FusionData.mMemData != null) {
            mBinding.tvMemInfo.setText(StringUtil.getPhoneNum(FusionData.mMemData.getPhone()));
        } else {
            getSupportDelegate().pop();
        }

        mBinding = DelegateMemTicketListBinding.bind(rootView);
        mBinding.tvBackHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getSupportDelegate().popTo(HomeDelegate.class, false);
            }
        });

        memPackageListAdapter.setonItemClickListener(new MemPackageListAdapter.OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                boolean needSingleTicket = false;
                for (MemTicketListEntity.BodyBean.MachineTicketInfosBean.MachineTicketInfos tickets : mPackageList.get(position).getMachineTicketInfos()) {
                    if (tickets.getTradeType().equals("3")) {
                        needSingleTicket = true;
                        break;
                    }
                }
                checkPrintInfo(mPackageList.get(position).getPackageCopiesId(), mPackageList.get(position).getSessionId(), mPackageList.get(position).getOrderNo(), needSingleTicket);
            }
        });

        initRefreshLayout();
    }

    private void initRefreshLayout() {

        mBinding.refreshLayout.autoRefresh();
        mBinding.refreshLayout.setEnableLoadMore(false);
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (FusionData.mMemData != null) {
                    mBinding.tvMemInfo.setText(StringUtil.getPhoneNum(FusionData.mMemData.getPhone()));
                    getMemTickets();
                }
            }
        });
    }

    private void checkPrintInfo(String packageCopiesId, String sessionId, String orderNo, boolean needSingleTicket) {
        CameraManager.takeVideo(getContext(), orderNo, getProxyActivity());
        if (timer != null) {
            timer.cancel();
        }
        mPrintData = new ArrayList<>();
        DialogUtil.showLoadingDialog(getContext(), "正在获取打印信息...");
        JSONObject params = new JSONObject();
        params.put("cashierNo", AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM));
        params.put("packageCopiesId", packageCopiesId);
        params.put("sessionId", sessionId);
        params.put("memberUuid", FusionData.mMemData.getUserId());
        params.put("needSingleTicket", needSingleTicket);
        LogUtils.saveLog2File(params.toString(), true);

        HttpHelper.RestClientPostRaw(params, HttpUrl.QUERY_PRINT_INFO,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        LogUtils.saveLog2File(response, false);
                        DialogUtil.dismissLoadingDialog();
                        try {
                            Type type = new TypeToken<MemPrintInfoEntity>() {
                            }.getType();
                            Gson gson = new Gson();
                            MemPrintInfoEntity mData = gson.fromJson(response, type);

                            if (mData.getHeader().getCode().equals(FusionCode.SUCCESS)) {
                                for (MemPrintInfoEntity.BodyBean data : mData.getBody()) {
                                    AtmosPreference.addCustomStringPre(FusionPre.PRINT_BRAND_NAME, data.getPrintBrandName());
                                    AtmosPreference.addCustomStringPre(FusionPre.PRINT_STORE_NAME, data.getPrintStoreName());
                                    if (StringUtil.isNotEmpty(data.getPrintId())) {
                                        mPrintData.add(data);
                                    }
                                }
                                mAllPrintTicketNum = mPrintData.size();
                                if (!mPrintData.isEmpty()) {
                                    showPrintTicketDialog(orderNo);
                                    startPrintTicket(orderNo);
                                } else {
                                    DialogUtil.showCardErrorDialog(MemTicketListDelegate.this, getContext(), "门票未配置打印物料,请联系工作人员！", "确定", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            DialogUtil.dismissErrorDialog();
                                            getSupportDelegate().popTo(HomeDelegate.class, false);
                                            FusionData.mMemData = null;
                                            EventBus.getDefault().post(new CheckTicketWaringEvent(new Bundle()));
                                        }
                                    });
                                }
                            } else if (mData.getHeader().getCode().equals("100009994")) {
                                DialogUtil.showCardErrorDialog(MemTicketListDelegate.this, getContext(), mData.getHeader().getMessage(), "确认", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        startCountDownTime(60);
                                        DialogUtil.dismissErrorDialog();
                                    }
                                });
                            } else if (mData.getHeader().getCode().equals("100009995")) {
                                DialogUtil.showCardErrorDialog(MemTicketListDelegate.this, getContext(), mData.getHeader().getMessage(), "确认", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        startCountDownTime(60);
                                        DialogUtil.dismissErrorDialog();
                                    }
                                });
                            } else {
                                DialogUtil.showCardErrorDialog(MemTicketListDelegate.this, getContext(), mData.getHeader().getMessage(), "确定", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        startCountDownTime(60);
                                        DialogUtil.dismissErrorDialog();
                                    }
                                });
                            }
                        } catch (Exception e) {
                            DialogUtil.showCardErrorDialog(MemTicketListDelegate.this, getContext(), e.getMessage(), "确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    startCountDownTime(60);
                                    DialogUtil.dismissErrorDialog();
                                }
                            });
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        DialogUtil.dismissLoadingDialog();
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {
                        DialogUtil.dismissLoadingDialog();
                    }
                });

    }

    private void getMemTickets() {

        JSONObject params = new JSONObject();
        params.put("cashierNo", AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM));
        params.put("memberUuid", FusionData.mMemData.getUserId());

        HttpHelper.RestClientPostRaw(params, HttpUrl.QUERY_MEM_TICKET,
                new ISuccess() {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void onSuccess(int code, String response) {
                        mBinding.refreshLayout.finishRefresh();
                        DialogUtil.dismissLoadingDialog();
                        try {
                            Type type = new TypeToken<MemTicketListEntity>() {
                            }.getType();
                            Gson gson = new Gson();
                            MemTicketListEntity mData = gson.fromJson(response, type);
                            if (mData.getHeader().getCode().equals(FusionCode.SUCCESS)) {
                                mPackageList = mData.getBody().getCanMachineTicketInfos();
                                if (mData.getBody().getCanMachineTicketInfos() != null && !mData.getBody().getCanMachineTicketInfos().isEmpty()) {
                                    memPackageListAdapter.setData(mData.getBody().getCanMachineTicketInfos(), true);
                                    memPackageListAdapter.notifyDataSetChanged();
                                }

                                if (mData.getBody().getNotCanMachineTicketInfos() != null && !mData.getBody().getNotCanMachineTicketInfos().isEmpty()) {
                                    cantMemPackageListAdapter.setData(mData.getBody().getNotCanMachineTicketInfos(), false);
                                    cantMemPackageListAdapter.notifyDataSetChanged();
                                    mBinding.linTips.setVisibility(View.VISIBLE);
                                } else {
                                    mBinding.linTips.setVisibility(View.GONE);
                                }

                            } else {
                                DialogUtil.showCardErrorDialog(getContext(), mData.getHeader().getMessage(), "确定");
                            }
                        } catch (Exception e) {
                            DialogUtil.showCardErrorDialog(getContext(), e.getMessage(), "确定");
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mBinding.refreshLayout.finishRefresh();
                        DialogUtil.showCardErrorDialog(getContext(), msg, "确定");
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {
                        mBinding.refreshLayout.finishRefresh();
                        DialogUtil.showCardErrorDialog(getContext(), getString(R.string.un_know_net_error), "确定");
                    }
                });

    }

    private void startPrintTicket(String orderNo) {
        if (mPrintData != null && !mPrintData.isEmpty()) {
            PrintInfoEntity data = new PrintInfoEntity();
            data.setId(mPrintData.get(0).getTicketId());
            data.setOrderNo(mPrintData.get(0).getOrderNo());
            data.setType(mPrintData.get(0).getTradeType());
            data.setQrCode(mPrintData.get(0).getBindUuid());
            data.setSessionNo(mPrintData.get(0).getSessionNo());
            data.setSessionDate(mPrintData.get(0).getSessionDate());
            data.setSessionTime(mPrintData.get(0).getSessionStartTime() + "-" + mPrintData.get(0).getSessionEndTime());
            data.setPrintWord(mPrintData.get(0).getPrintedWord());
            data.setTicketPrintName(mPrintData.get(0).getTicketPrintName());
            PrintUtil.doPrint(requireContext(), mPrintData.get(0).getPrintId(), tvPrintErrorInfo, tvRetry, data, getProxyActivity());
        } else {
            new android.os.Handler().postDelayed(CameraManager::stopRecording, 10000); // 10 秒后停止录制
            FusionCode.SCAN_TYPE = FusionCode.CANCEL;
            tvBackNow.setVisibility(View.VISIBLE);
            tvPrintStatus.setText("打印完成");
            tvPrintGetTicket.setVisibility(View.VISIBLE);
            tvPrintFinishTime.setVisibility(View.VISIBLE);
            startCountDownTimeFinish(5,orderNo);
        }
        tvTicketOutNum.setText(Html.fromHtml(String.format(getString(R.string.print_ticket_num), String.valueOf(mAllPrintTicketNum - mPrintData.size()), String.valueOf(mAllPrintTicketNum))));
    }

    @SuppressLint("SetTextI18n")
    public void showPrintTicketDialog(String orderNo) {
        if (mPrintTicketDialog != null) {
            mPrintTicketDialog.dismiss();
        } else {
            mPrintTicketDialog = new Dialog(requireContext(), com.qsmx.core.R.style.dialog);
        }
        SoundPlayUtils.play(4);

        mPrintTicketDialog.setCancelable(false);
        Window window = mPrintTicketDialog.getWindow();
        window.setContentView(R.layout.dialog_ticket_out);
        int width = (int) (DimenUtil.getScreenWidth() * 0.8);
        window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);

        tvPrintStatus = window.findViewById(R.id.tv_print_status);
        tvTicketOutNum = window.findViewById(R.id.tv_ticket_out_num);
        tvPrintGetTicket = window.findViewById(R.id.tv_print_get_ticket);
        tvPrintFinishTime = window.findViewById(R.id.tv_print_finish_time);
        tvBackNow = window.findViewById(R.id.tv_back_now);
        tvPrintErrorInfo = window.findViewById(R.id.tv_print_error_info);
        tvRetry = window.findViewById(R.id.tv_retry);

        AppCompatTextView tvOrderNo = window.findViewById(R.id.tv_order_no);

        tvOrderNo.setText("订单号：" + orderNo);

        tvRetry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startPrintTicket(orderNo);
                tvRetry.setVisibility(View.GONE);
                tvPrintErrorInfo.setVisibility(View.GONE);
            }
        });

        tvBackNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPrintTicketDialog.dismiss();
                FileUtil.deleteFolderFile(SaveHelper.getSaveVideoBasePath(orderNo));
                getSupportDelegate().popTo(HomeDelegate.class, false);
                FusionData.mMemData = null;
                EventBus.getDefault().post(new CheckTicketWaringEvent(new Bundle()));
            }
        });
        mPrintTicketDialog.show();
    }


    private void startCountDownTime(final long time) {
        if (timer != null) {
            timer.cancel();
        }
        timer = new CountDownTimerUtil(time * 1000, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                mBinding.tvBackHome.setText(String.format(getString(R.string.back_home), String.valueOf(millisUntilFinished / 1000)));
            }

            @Override
            public void onFinish() {
                getSupportDelegate().popTo(HomeDelegate.class, false);
            }
        };
        timer.start();// 开始计时
    }

    private void startCountDownTimeFinish(final long time, String orderNo) {
        if (finishTimer != null) {
            finishTimer.cancel();
        }
        finishTimer = new CountDownTimerUtil(time * 1000, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                tvPrintFinishTime.setText(String.format(getString(R.string.finish_time), String.valueOf(millisUntilFinished / 1000)));
            }

            @Override
            public void onFinish() {
                if (mPrintTicketDialog != null) {
                    mPrintTicketDialog.dismiss();
                }
                FileUtil.deleteFolderFile(SaveHelper.getSaveVideoBasePath(orderNo));
                getSupportDelegate().popTo(HomeDelegate.class, false);
                FusionData.mMemData = null;
                EventBus.getDefault().post(new CheckTicketWaringEvent(new Bundle()));
            }
        };
        finishTimer.start();// 开始计时
    }

    private void printFinish(String printId, String orderNo, String ticketId) {
        DialogUtil.showLoadingDialog(requireContext(), "正在记录门票信息...");
        long orderNoTime = System.currentTimeMillis();
        String serialNo = "LS" + AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM) + orderNoTime + StringUtil.getRandomNumString(6);

        JSONObject params = new JSONObject();
        params.put("serialNo", serialNo);
        params.put("cashierNo", AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM));
        params.put("printId", printId);
        params.put("orderNo", orderNo);
        params.put("ticketId", ticketId);
        params.put("changeNum", "1");
        params.put("changeType", "1");
        if (printId.equals("1")) {
            params.put("beforeNum", AtmosPreference.getCustomStringPre(FusionPre.PRINT_ONE_TICKET_NUM));
        } else if (printId.equals("2")) {
            params.put("beforeNum", AtmosPreference.getCustomStringPre(FusionPre.PRINT_TWO_TICKET_NUM));
        } else if (printId.equals("3")) {
            params.put("beforeNum", AtmosPreference.getCustomStringPre(FusionPre.PRINT_THREE_TICKET_NUM));
        }

        HttpHelper.RestClientPostRaw(params, HttpUrl.PRINT_RECORD,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        DialogUtil.dismissLoadingDialog();
                        Type type = new TypeToken<BaseEntity>() {
                        }.getType();
                        Gson gson = new Gson();
                        BaseEntity mData = gson.fromJson(response, type);
                        if (mData.getHeader().getCode().equals("200")) {
                            if (printId.equals("1")) {
                                AtmosPreference.addCustomStringPre(FusionPre.PRINT_ONE_TICKET_NUM, String.valueOf(StringUtil.IntegerValueOf(AtmosPreference.getCustomStringPre(FusionPre.PRINT_ONE_TICKET_NUM), 0) - 1));
                            } else if (printId.equals("2")) {
                                AtmosPreference.addCustomStringPre(FusionPre.PRINT_TWO_TICKET_NUM, String.valueOf(StringUtil.IntegerValueOf(AtmosPreference.getCustomStringPre(FusionPre.PRINT_TWO_TICKET_NUM), 0) - 1));
                            } else if (printId.equals("3")) {
                                AtmosPreference.addCustomStringPre(FusionPre.PRINT_THREE_TICKET_NUM, String.valueOf(StringUtil.IntegerValueOf(AtmosPreference.getCustomStringPre(FusionPre.PRINT_THREE_TICKET_NUM), 0) - 1));
                            }
                            mPrintData.remove(0);
                            startPrintTicket(orderNo);
                        } else {
                            DialogUtil.showCardErrorDialog(MemTicketListDelegate.this, requireContext(), mData.getHeader().getMessage(), "重试", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    DialogUtil.dismissErrorDialog();
                                    printFinish(printId, orderNo, ticketId);
                                }
                            });
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        DialogUtil.dismissLoadingDialog();
                        DialogUtil.showCardErrorDialog(MemTicketListDelegate.this, requireContext(), msg, "重试", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                DialogUtil.dismissErrorDialog();
                                printFinish(printId, orderNo, ticketId);
                            }
                        });
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {
                        DialogUtil.dismissLoadingDialog();
                        DialogUtil.showCardErrorDialog(MemTicketListDelegate.this, requireContext(), getString(R.string.un_know_net_error), "重试", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                DialogUtil.dismissErrorDialog();
                                printFinish(printId, orderNo, ticketId);
                            }
                        });
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPrintFinishEvent(PrintFinishEvent event) {
        if (isVisible()) {
            if (event != null && event.getData() != null) {
                printFinish(mPrintData.get(0).getPrintId(), mPrintData.get(0).getOrderNo(), mPrintData.get(0).getTicketId());
            }
        }
    }


    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        startCountDownTime(60);
        if (FusionData.mMemData != null) {
            mBinding.tvMemInfo.setText(StringUtil.getPhoneNum(FusionData.mMemData.getPhone()));
        }
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        if (timer != null) {
            timer.cancel();
        }
        if (finishTimer != null) {
            finishTimer.cancel();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
        if (finishTimer != null) {
            finishTimer.cancel();
        }
        if (mPrintTicketDialog != null && mPrintTicketDialog.isShowing()) {
            mPrintTicketDialog.dismiss();
        }

        EventBus.getDefault().unregister(this);
        FusionData.mMemData = null;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }
}
